package controllers

import (
	"github.com/360EntSecGroup-Skylar/excelize"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
	"math"
	"net/url"
	"nspel/entity"
	"nspel/model"
	"nspel/nspel"
	"nspel/util"
	"strconv"
	"time"
)

type AreasManageController struct {
	beego.Controller
}

func (c *AreasManageController) PostAreasImportCheck() {
	defer c.ServeJSON()
	requestData := new(model.PostAreasImport)
	err := requestData.Validate(&c.Controller)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
		return
	}
	excelData, err := util.TryParseXlsx(&requestData.ImportFile)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
		return
	}
	msg, _, _, err := util.ValidateAreaImport(&excelData)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
		nspel.Error(err)
		return
	}
	c.Data["json"] = msg
}

func (c *AreasManageController) PostAreasImportSubmit() {
	c.EnableRender = false
	requestData := new(model.PostAreasImport)
	err := requestData.Validate(&c.Controller)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
		return
	}
	excelData, err := util.TryParseXlsx(&requestData.ImportFile)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
		return
	}
	msg, create, update, err := util.ValidateAreaImport(&excelData)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
		nspel.Error(err)
		return
	}
	if msg.Result {
		err = util.AreaImport(&create, &update)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
	}
	c.Data["json"] = msg
	c.ServeJSON()
}

func (c *AreasManageController) GetAreaSelector() {
	defer c.ServeJSON()
	authority, ok := c.Ctx.Input.Session("authority").(byte)
	if !ok {
		c.Data["json"] = model.ErrorRes{RetCode: 1, Msg: "session失效"}
		return
	}
	uid, ok := c.Ctx.Input.Session("uid").(int64)
	if !ok {
		c.Data["json"] = model.ErrorRes{RetCode: 1, Msg: "session失效"}
		return
	}
	if authority == entity.ManagerAuthority.Administrator {
		cityId, err := c.GetInt64("city-id")
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求错误"}
		} else {
			area := new(entity.Area)
			areas, err := area.SelectAllByCityId(cityId)
			if err != nil {
				if err == orm.ErrNoRows {
					c.Data["json"] = model.GetAreaSelectorRes{RetCode: 0}
				} else {
					c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求错误"}
				}
			} else {
				res := model.GetAreaSelectorRes{RetCode: 0}
				res.Area = make([]model.AreaSelector, len(areas))
				for i := 0; i < len(res.Area); i++ {
					res.Area[i].Id = areas[i].Id
					res.Area[i].Value = areas[i].Name
				}
				c.Data["json"] = res
			}
		}
	} else if authority != entity.ManagerAuthority.Area {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
	} else {
		area := new(entity.Area)
		err := area.SelectAllByUserId(uid)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		areas, err := area.SelectAllByCityId(area.CityId)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		res := model.GetAreaSelectorRes{RetCode: 0}
		res.Area = make([]model.AreaSelector, len(areas))
		for i := 0; i < len(res.Area); i++ {
			res.Area[i].Id = areas[i].Id
			res.Area[i].Value = areas[i].Name
		}
		c.Data["json"] = res
	}
}

/*
func (c *AreasManageController) GetJoinSelector () {
	c.EnableRender = false
	provinceId, err1 := c.GetInt64("province-id")
	cityId, err2 := c.GetInt64("city-id")
}*/

func (c *AreasManageController) GetAreasList() {
	defer c.ServeJSON()
	req := model.GetAreasList{}
	b := req.Validate("province-id", "city-id", "area-name", "join-year", "page-size", "current-page", &c.Controller)
	if !b {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求错误"}
	} else {
		count, areas, err := util.GetAreasList(req.ProvinceId, req.CityId, req.AreaName, req.JoinYear, req.PageSize, req.CurrentPage)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
		} else {
			resData := model.GetAreasListRes{RetCode: 0}
			resData.Total = count
			for i := 0; i < len(*areas); i++ {
				areasList := model.AreasList{}
				areasList.Id = (*areas)[i].Id
				areasList.ProvinceCityName, err = util.GetProvinceCityName((*areas)[i].ProvinceId, (*areas)[i].CityId)
				if err != nil {
					c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
					nspel.Error(err)
					return
				}
				areasList.Name = (*areas)[i].Name
				areasList.SchoolNum = (*areas)[i].AllSchoolNum
				if (*areas)[i].IsExperiment {
					areasList.IsExperiment = "是"
				} else {
					areasList.IsExperiment = "否"
				}
				areasList.ExperimentNum = (*areas)[i].AuthorizedSchoolNum
				areasList.StandoutNum = (*areas)[i].StandoutSchoolNum
				areasList.Contact = (*areas)[i].Contact.String
				areasList.ContactPhone = (*areas)[i].ContactPhone.String
				areasList.ContactEmail = (*areas)[i].ContactEmail.String
				areasList.JoinYear = int64((*areas)[i].JoinYear.Int64)
				areasList.ExperimentAt = (*areas)[i].ExperimentAt
				areasList.StandoutAt = (*areas)[i].StandoutAt
				areasList.ContactAddress = (*areas)[i].ContactAddress.String
				resData.Data = append(resData.Data, areasList)
			}
			c.Data["json"] = resData
		}
	}
}

func (c *AreasManageController) PostAreaModify() {
	defer c.ServeJSON()
	var requestData model.PostAreaModify
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求错误"}
		return
	}
	valid := validation.Validation{}
	b, err := valid.Valid(&requestData)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
		return
	}
	if !b {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求错误"}
		return
	}
	if len(requestData.ContactPhone) > 0 {
		valid.Phone(requestData.ContactPhone, "contactPhone")
		if valid.HasErrors() {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求错误"}
			return
		}
	}
	if len(requestData.ContactEmail) > 0 {
		valid.Email(requestData.ContactEmail, "contactEmail")
		if valid.HasErrors() {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求错误"}
			return
		}
	}
	area := new(entity.Area)
	err = area.SelectAllById(requestData.Id)
	if err != nil {
		if err == orm.ErrNoRows {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求修改的试验区不存在"}
		} else {
			nspel.Error(err)
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
		}
		return
	}
	area.Id = requestData.Id
	area.AllSchoolNum = requestData.SchoolNum
	area.IsExperiment = requestData.IsExperiment
	if requestData.JoinYear != 0 && requestData.JoinYear <= 2000 {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求加入年份非法"}
		return
	} else if requestData.JoinYear > 2000 {
		area.JoinYear.Int64 = int64(requestData.JoinYear)
		area.JoinYear.Valid = true
	} else {
		area.JoinYear.Valid = false
	}
	area.Contact = util.GetNullString(requestData.Contact)
	area.ContactEmail = util.GetNullString(requestData.ContactEmail)
	area.ContactAddress = util.GetNullString(requestData.ContactAddress)
	area.ExperimentAt = requestData.ExperimentAt
	area.StandoutAt = requestData.StandoutAt
	deleteManagerId := int64(0)
	if len(requestData.ContactPhone) > 0 && !area.UserId.Valid {
		if area.ContactPhone.String != requestData.ContactPhone {
			deleteManagerId = area.UserId.Int64
			area.ContactPhone.String = requestData.ContactPhone
			area.ContactPhone.Valid = true
			manage := new(entity.Manager)
			err := manage.SelectAllByUserName(area.ContactPhone.String)
			if err != nil {
				if err == orm.ErrNoRows {
					id, err := manage.Register(area.ContactPhone.String, area.ContactPhone.String, entity.ManagerAuthority.Area)
					if err != nil {
						c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
						nspel.Error(err)
						return
					}
					area.UserId = id
				} else {
					c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
					nspel.Error(err)
					return
				}
			} else {
				c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "联系电话已经是其他账户的账号"}
				return
			}
		}
	} else if len(requestData.ContactPhone) > 0 {
		area.ContactPhone = util.GetNullString(requestData.ContactPhone)
	}
	err = area.Update("all_school_num", "is_experiment", "join_year", "contact", "contactPhone", "user_id", "contact_email", "contact_address", "experiment_at", "standout_at")
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
		nspel.Error(err)
		return
	}
	if deleteManagerId != 0 {
		manager := entity.Manager{}
		err = manager.DeleteById(deleteManagerId)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
	}
	nspel.RedisKeyDelete("area")
	nspel.RedisKeyDelete("manager")
	c.Data["json"] = model.ErrorRes{RetCode: 0, Msg: "修改成功"}
}

func (c *AreasManageController) PostAreaAdd() {
	defer c.ServeJSON()
	var requestData model.PostAreaAdd
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求错误"}
		return
	}
	b, err := requestData.Validate()
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
		nspel.Error(err)
		return
	} else if !b {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求错误"}
		return
	}
	area := new(entity.Area)
	area.CountryId = requestData.CountryId
	area.ProvinceId = requestData.ProvinceId
	area.CityId = requestData.CityId
	area.Name = requestData.Name
	area.AllSchoolNum = requestData.SchoolNum
	area.IsExperiment = requestData.IsExperiment
	area.JoinYear = util.GetNullInt64(int64(requestData.JoinYear), 0)
	area.Contact = util.GetNullString(requestData.Contact)
	area.ContactPhone = util.GetNullString(requestData.ContactPhone)
	area.ContactEmail = util.GetNullString(requestData.ContactEmail)
	area.ContactAddress = util.GetNullString(requestData.ContactAddress)
	area.ExperimentAt = requestData.ExperimentAt
	area.StandoutAt = requestData.StandoutAt
	if area.ContactPhone.Valid {
		manager := new(entity.Manager)
		area.UserId, err = manager.Register(area.ContactPhone.String, area.ContactPhone.String, entity.ManagerAuthority.Area)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
	}
	err = area.Insert()
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
		nspel.Error(err)
		return
	}
	nspel.RedisKeyDelete("manager")
	nspel.RedisKeyDelete("area")
	c.Data["json"] = model.ErrorRes{RetCode: 0, Msg: "添加成功"}
}

func (c *AreasManageController) DeleteArea() {
	defer c.ServeJSON()
	var requestData model.DeleteArea
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求错误"}
		return
	}
	b, err, areas := requestData.Validate()
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
		nspel.Error(err)
		return
	} else if !b {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求错误"}
		return
	}
	for i := 0; i < len(areas); i++ {
		if areas[i].UserId.Valid {
			err = areas[i].DeleteById(areas[i].Id)
			if err != nil {
				c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
				nspel.Error(err)
				return
			}
			manager := new(entity.Manager)
			err = manager.DeleteById(int64(areas[i].UserId.Int64))
			if err != nil {
				c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
				nspel.Error(err)
				return
			}
		} else {
			err = areas[i].DeleteById(areas[i].Id)
			if err != nil {
				c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
				nspel.Error(err)
				return
			}
		}
	}
	defer nspel.ResdisKeysDelete("area", "manager")
	c.Data["json"] = model.ErrorRes{RetCode: 0, Msg: "删除成功"}
}

func (c *AreasManageController) PostAreaNameValidateExist() {
	defer c.ServeJSON()
	var requestData model.PostAreaNameValidateExist
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求错误"}
		return
	}
	b, err := requestData.Validate()
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
		nspel.Error(err)
		return
	}
	if !b {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求错误"}
		return
	}
	area := new(entity.Area)
	err = area.SelectAllByCityIdName(requestData.CityId, requestData.Name)
	if err != nil {
		if err != orm.ErrNoRows {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		} else {
			c.Data["json"] = map[string]interface{}{"retCode": 0, "result": true}
		}
	} else {
		c.Data["json"] = map[string]interface{}{"retCode": 0, "result": false, "msg": "区名称重复"}
	}
}

func (c *AreasManageController) GetAreaOverview() {
	defer c.ServeJSON()
	authority, ok := c.Ctx.Input.Session("authority").(byte)
	if !ok {
		c.Data["json"] = model.ErrorRes{RetCode: 1, Msg: "session失效"}
		return
	}
	uid, ok := c.Ctx.Input.Session("uid").(int64)
	if !ok {
		c.Data["json"] = model.ErrorRes{RetCode: 1, Msg: "session失效"}
		return
	}
	var areaId int64
	if authority == entity.ManagerAuthority.Administrator {
		schoolId, err := c.GetInt64("school-id")
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
			return
		}
		school := new(entity.School)
		err = school.SelectAllById(schoolId)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		areaId = school.ExperimentAreaId
	} else if authority == entity.ManagerAuthority.Area {
		area := new(entity.Area)
		err := area.SelectAllByUserId(uid)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		areaId = area.Id
	} else if authority == entity.ManagerAuthority.School {
		school := new(entity.School)
		err := school.SelectAllByUserId(uid)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		areaId = school.ExperimentAreaId
	}
	school := new(entity.School)
	schoolCount, err := school.SelectCountByExperimentAreaId(areaId)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
		nspel.Error(err)
		return
	}
	score := new(entity.Score)
	lastYearDate := time.Now().AddDate(-1, 0, 0).Format("2006-01-02")
	ormEng := nspel.GetOrmEngine().QueryTable(score.TableName()).Filter("experiment_area_id", areaId).Filter("missing_test_num", 0).Filter("physical_total_score__gte", 90).Filter("measurement_date__gte", lastYearDate)
	excellentNum, err := score.CustomCount(&ormEng, "experimentAreaId["+strconv.FormatInt(areaId, 10)+"].missingTestNum[0].physicalTotalScore[>=90].measurementData[>="+lastYearDate+"].count")
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
		nspel.Error(err)
		return
	}
	ormEng = nspel.GetOrmEngine().QueryTable(score.TableName()).Filter("experiment_area_id", areaId).Filter("missing_test_num", 0).Filter("physical_total_score__lt", 80).Filter("physical_total_score__gte", 60).Filter("measurement_date__gte", lastYearDate)
	passingNum, err := score.CustomCount(&ormEng, "experimentAreaId["+strconv.FormatInt(areaId, 10)+"].missingTestNum[0].physicalTotalScore[<80].physicalTotalScore[>=60].measurementData[>="+lastYearDate+"].count")
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
		nspel.Error(err)
		return
	}
	ormEng = nspel.GetOrmEngine().QueryTable(score.TableName()).Filter("experiment_area_id", areaId).Filter("missing_test_num", 0).Filter("measurement_date__gte", lastYearDate)
	allNum, err := score.CustomCount(&ormEng, "experimentAreaId["+strconv.FormatInt(areaId, 10)+"].missingTestNum[0].measurementData[>="+lastYearDate+"].count")
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
		nspel.Error(err)
		return
	}
	c.Data["json"] = map[string]interface{}{"retCode": 0, "data": []float64{float64(schoolCount), float64(excellentNum) / float64(allNum), float64(passingNum) / float64(allNum)}}
}

func (c *AreasManageController) GetSchoolRank() {
	defer c.ServeJSON()
	authority, ok := c.Ctx.Input.Session("authority").(byte)
	if !ok {
		c.Data["json"] = model.ErrorRes{RetCode: 1, Msg: "session失效"}
		return
	}
	uid, ok := c.Ctx.Input.Session("uid").(int64)
	if !ok {
		c.Data["json"] = model.ErrorRes{RetCode: 1, Msg: "session失效"}
		return
	}
	var areaId int64
	if authority == entity.ManagerAuthority.Administrator {
		schoolId, err := c.GetInt64("school-id")
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "请求无效"}
			return
		}
		school := new(entity.School)
		err = school.SelectAllById(schoolId)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		areaId = school.ExperimentAreaId
	} else if authority == entity.ManagerAuthority.Area {
		area := new(entity.Area)
		err := area.SelectAllByUserId(uid)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		areaId = area.Id
	} else if authority == entity.ManagerAuthority.School {
		school := new(entity.School)
		err := school.SelectAllByUserId(uid)
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		areaId = school.ExperimentAreaId
	}
	school := new(entity.School)
	schools, err := school.SelectAllByExperimentAreaIdOrderByScoreDesc(areaId, 5)
	if err != nil {
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
		nspel.Error(err)
		return
	}
	res := model.GetSchoolRankRes{}
	res.Data = make([]model.SchoolRankList, len(schools))
	score := new(entity.Score)
	lastYearDate := time.Now().AddDate(-1, 0, 0).Format("2006-01-02")
	for i := 0; i < len(schools); i++ {
		res.Data[i].Name = schools[i].Name
		res.Data[i].Rank = int64(i) + 1
		ormEng := nspel.GetOrmEngine().QueryTable(score.TableName()).Filter("school_id", schools[i].Id).Filter("missing_test_num", 0).Filter("physical_total_score__gte", 90).Filter("measurement_date__gte", lastYearDate)
		excellentNum, err := score.CustomCount(&ormEng, "schoolId["+strconv.FormatInt(schools[i].Id, 10)+"].missingTestNum[0].physicalTotalScore[>=90].measurementData[>="+lastYearDate+"].count")
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		ormEng = nspel.GetOrmEngine().QueryTable(score.TableName()).Filter("school_id", schools[i].Id).Filter("missing_test_num", 0).Filter("physical_total_score__lt", 80).Filter("physical_total_score__gte", 60).Filter("measurement_date__gte", lastYearDate)
		passingNum, err := score.CustomCount(&ormEng, "schoolId["+strconv.FormatInt(schools[i].Id, 10)+"].missingTestNum[0].physicalTotalScore[<80].physicalTotalScore[>=60].measurementData[>="+lastYearDate+"].count")
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		ormEng = nspel.GetOrmEngine().QueryTable(score.TableName()).Filter("school_id", schools[i].Id).Filter("missing_test_num", 0).Filter("measurement_date__gte", lastYearDate)
		allNum, err := score.CustomCount(&ormEng, "schoolId["+strconv.FormatInt(schools[i].Id, 10)+"].missingTestNum[0].measurementData[>="+lastYearDate+"].count")
		if err != nil {
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			nspel.Error(err)
			return
		}
		if allNum != 0 {
			res.Data[i].ExcellentRate = float64(excellentNum) / float64(allNum)
			res.Data[i].PassingRate = float64(passingNum) / float64(allNum)
		}
	}
	c.Data["json"] = res
}

func (c *AreasManageController) GetAreaExport() {
	c.EnableRender = false
	req := model.GetAreaExportReq{}
	b := req.Validate("province-id", "city-id", "area-name", "join-year", &c.Controller)
	if !b {
		c.Ctx.ResponseWriter.Status = 400
	} else {
		_, areas, err := util.GetAreasList(req.ProvinceId, req.CityId, req.AreaName, req.JoinYear, math.MaxInt64, 1)
		if err != nil {
			c.Ctx.ResponseWriter.Status = 500
			nspel.Error(err)
		} else {
			xlsx := excelize.NewFile()
			widthMap := make(map[string]float64)
			xlsx.SetSheetName("Sheet1", "试验区")
			xlsx.SetCellValue("试验区", "A1", "序号")
			widthMap["A"] = math.Max(widthMap["A"], util.GetStrLength("序号")+1)
			xlsx.SetCellValue("试验区", "B1", "省份")
			widthMap["B"] = math.Max(widthMap["B"], util.GetStrLength("省份")+1)
			xlsx.SetCellValue("试验区", "C1", "城市")
			widthMap["C"] = math.Max(widthMap["C"], util.GetStrLength("城市")+1)
			xlsx.SetCellValue("试验区", "D1", "实验区名称")
			widthMap["D"] = math.Max(widthMap["D"], util.GetStrLength("实验区名称")+1)
			xlsx.SetCellValue("试验区", "E1", "负责人")
			widthMap["E"] = math.Max(widthMap["E"], util.GetStrLength("负责人")+1)
			xlsx.SetCellValue("试验区", "F1", "联系电话")
			widthMap["F"] = math.Max(widthMap["F"], util.GetStrLength("联系电话")+1)
			xlsx.SetCellValue("试验区", "G1", "邮箱")
			widthMap["G"] = math.Max(widthMap["G"], util.GetStrLength("邮箱")+1)
			xlsx.SetCellValue("试验区", "H1", "联系地址")
			widthMap["H"] = math.Max(widthMap["H"], util.GetStrLength("联系地址")+1)
			xlsx.SetCellValue("试验区", "I1", "学校总数(所)")
			widthMap["I"] = math.Max(widthMap["I"], util.GetStrLength("学校总数(所)")+1)
			xlsx.SetCellValue("试验区", "J1", "实验校（所）")
			widthMap["J"] = math.Max(widthMap["J"], util.GetStrLength("实验校（所）")+1)
			xlsx.SetCellValue("试验区", "K1", "示范校（所）")
			widthMap["K"] = math.Max(widthMap["K"], util.GetStrLength("示范校（所）")+1)
			xlsx.SetCellValue("试验区", "L1", "实验区颁牌时间")
			widthMap["L"] = math.Max(widthMap["L"], util.GetStrLength("实验区颁牌时间")+1)
			xlsx.SetCellValue("试验区", "M1", "示范区颁牌")
			widthMap["M"] = math.Max(widthMap["M"], util.GetStrLength("示范区颁牌")+1)
			xlsx.SetCellValue("试验区", "N1", "加入年份")
			widthMap["N"] = math.Max(widthMap["N"], util.GetStrLength("加入年份")+1)
			for i := 0; i < len(*areas); i++ {
				xlsx.SetCellValue("试验区", "A"+strconv.Itoa(i+2), i+1)
				widthMap["A"] = math.Max(widthMap["A"], util.GetStrLength(strconv.Itoa(i+1))+1)
				province := new(entity.Province)
				err = province.SelectAllById((*areas)[i].ProvinceId)
				if err != nil {
					c.Ctx.ResponseWriter.Status = 500
					nspel.Error(err)
					return
				}
				xlsx.SetCellValue("试验区", "B"+strconv.Itoa(i+2), province.Name)
				widthMap["B"] = math.Max(widthMap["B"], util.GetStrLength(province.Name)+1)
				city := new(entity.City)
				err = city.SelectAllById((*areas)[i].CityId)
				if err != nil {
					c.Ctx.ResponseWriter.Status = 500
					nspel.Error(err)
					return
				}
				xlsx.SetCellValue("试验区", "C"+strconv.Itoa(i+2), city.Name)
				widthMap["C"] = math.Max(widthMap["C"], util.GetStrLength(city.Name)+1)
				xlsx.SetCellValue("试验区", "D"+strconv.Itoa(i+2), (*areas)[i].Name)
				widthMap["D"] = math.Max(widthMap["D"], util.GetStrLength((*areas)[i].Name)+1)
				xlsx.SetCellValue("试验区", "E"+strconv.Itoa(i+2), (*areas)[i].Contact.String)
				widthMap["E"] = math.Max(widthMap["E"], util.GetStrLength((*areas)[i].Contact.String)+1)
				xlsx.SetCellValue("试验区", "F"+strconv.Itoa(i+2), (*areas)[i].ContactPhone.String)
				widthMap["F"] = math.Max(widthMap["F"], util.GetStrLength((*areas)[i].ContactPhone.String)+1)
				xlsx.SetCellValue("试验区", "G"+strconv.Itoa(i+2), (*areas)[i].ContactEmail.String)
				widthMap["G"] = math.Max(widthMap["G"], util.GetStrLength((*areas)[i].ContactEmail.String)+1)
				xlsx.SetCellValue("试验区", "H"+strconv.Itoa(i+2), (*areas)[i].ContactAddress.String)
				widthMap["H"] = math.Max(widthMap["H"], util.GetStrLength((*areas)[i].ContactAddress.String)+1)
				xlsx.SetCellValue("试验区", "I"+strconv.Itoa(i+2), (*areas)[i].AllSchoolNum)
				widthMap["I"] = math.Max(widthMap["I"], util.GetStrLength(strconv.FormatInt((*areas)[i].AllSchoolNum, 10))+1)
				xlsx.SetCellValue("试验区", "J"+strconv.Itoa(i+2), (*areas)[i].AuthorizedSchoolNum)
				widthMap["J"] = math.Max(widthMap["J"], util.GetStrLength(strconv.FormatInt((*areas)[i].AuthorizedSchoolNum, 10))+1)
				xlsx.SetCellValue("试验区", "K"+strconv.Itoa(i+2), (*areas)[i].StandoutSchoolNum)
				widthMap["K"] = math.Max(widthMap["K"], util.GetStrLength(strconv.FormatInt((*areas)[i].StandoutSchoolNum, 10))+1)
				if !(*areas)[i].ExperimentAt.IsZero() {
					xlsx.SetCellValue("试验区", "L"+strconv.Itoa(i+2), (*areas)[i].ExperimentAt.Format("2006/01/02"))
					widthMap["L"] = math.Max(widthMap["L"], util.GetStrLength((*areas)[i].ExperimentAt.Format("2006/01/02"))+1)
				}
				if !(*areas)[i].StandoutAt.IsZero() {
					xlsx.SetCellValue("试验区", "M"+strconv.Itoa(i+2), (*areas)[i].StandoutAt.Format("2006/01/02"))
					widthMap["M"] = math.Max(widthMap["M"], util.GetStrLength((*areas)[i].StandoutAt.Format("2006/01/02"))+1)
				}
				if (*areas)[i].JoinYear.Valid {
					xlsx.SetCellValue("试验区", "N"+strconv.Itoa(i+2), (*areas)[i].JoinYear.Int64)
					widthMap["N"] = math.Max(widthMap["N"], util.GetStrLength(strconv.FormatInt((*areas)[i].JoinYear.Int64, 10))+1)
				}
			}
			for k, v := range widthMap {
				xlsx.SetColWidth("试验区", k, k, v)
			}
			buffer, err := xlsx.WriteToBuffer()
			if err != nil {
				c.Ctx.ResponseWriter.Status = 500
				nspel.Error(err)
				return
			}
			c.Ctx.Output.Header("Content-Disposition", "attachment; filename="+url.PathEscape("试验区.xlsx"))
			c.Ctx.Output.Header("Content-Description", "File Transfer")
			c.Ctx.Output.Header("Content-Type", "application/octet-stream")
			c.Ctx.Output.Header("Content-Transfer-Encoding", "binary")
			c.Ctx.Output.Header("Expires", "0")
			c.Ctx.Output.Header("Cache-Control", "must-revalidate")
			c.Ctx.Output.Header("Pragma", "public")
			c.Ctx.ResponseWriter.Write(buffer.Bytes())
		}
	}
}
